/*
 * @Author: liusheng
 * @Date: 2022-04-18 17:05:45
 * @LastEditors: liusheng
 * @LastEditTime: 2022-04-18 17:44:54
 * @Description: 剑指 Offer II 032. 有效的变位词
 * email:liusheng613@126.com
 * Copyright (c) 2022 by liusheng/liusheng, All Rights Reserved. 
 * 
 * 剑指 Offer II 032. 有效的变位词
给定两个字符串 s 和 t ，编写一个函数来判断它们是不是一组变位词（字母异位词）。

注意：若 s 和 t 中每个字符出现的次数都相同且字符顺序不完全相同，则称 s 和 t 互为变位词（字母异位词）。

 

示例 1:

输入: s = "anagram", t = "nagaram"
输出: true
示例 2:

输入: s = "rat", t = "car"
输出: false
示例 3:

输入: s = "a", t = "a"
输出: false
 

提示:

1 <= s.length, t.length <= 5 * 104
s and t 仅包含小写字母
 

进阶: 如果输入字符串包含 unicode 字符怎么办？你能否调整你的解法来应对这种情况？
 */

#include <array>
#include <unordered_map>
using namespace std;

//use character count for every string to record the character's appearance time
//then compare
class Solution {
public:
    bool isAnagram(string s, string t) {
        int m = s.size();
        int n = t.size();

        if (m != n)
        {
            return false;
        }

        array<int,26> chCount = {0};
        bool allSame = true;
        for (int i = 0; i < m;++i)
        {
            if (s[i] != t[i])
            {
                allSame = false;
            }
            ++chCount[s[i] - 'a'];
            --chCount[t[i] - 'a'];
        }

        for (auto cnt: chCount)
        {
            if (cnt)
            {
                return false;
            }
        }

        return !allSame;
    }
};

//using unordered_map(hashmap) to count the character's appearance time
//this can deal with other character,not only alpha
class Solution2 {
public:
    bool isAnagram(string s, string t) {
        int m = s.size();
        int n = t.size();

        if (m != n)
        {
            return false;
        }

        unordered_map<char,int> chCnt;
        bool allSame = true;
        for (int i = 0; i < m;++i)
        {
            if (s[i] != t[i])
            {
                allSame = false;
            }
            ++chCnt[s[i]];
            --chCnt[t[i]];
        }

        for (auto cnt: chCnt)
        {
            if (cnt.second)
            {
                return false;
            }
        }

        return !allSame;
    }
};
